package org.itboys.mobile.controller.mobile.order;

import com.google.common.collect.Maps;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.ErrorException;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.kitchen.entity.mysql.order.KitchenOrder;
import org.itboys.kitchen.util.MobileSignUtils;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.count.KitchenCountDto;
import org.itboys.mobile.dto.order.KitchenOrderDto;
import org.itboys.mobile.service.mongo.mobile.KitchenMobileCartService;
import org.itboys.mobile.service.mysql.mobile.order.KitchenMobileOrderService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年2月9日
 * 联系方式 ：empty90911@126.com
 * 描述：农厨_订单_controller。
 *
 */
@Controller
@RequestMapping("/kitchen/mobile/order")
public class KitchenMobileOrderController extends BaseController{
    @Autowired
    private KitchenMobileOrderService orderService;


    @RequestMapping(value="/createOrder",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】创建订单。")
    public void createOrder(HttpServletRequest request,
             HttpServletResponse response,
                        @ApiParam(required = true, name = "cartIds", value = "购物车ID集合(非商品ID)") @RequestParam(value = "cartIds", required = true) List<Long> cartIds,
                        @ApiParam(required = false, name = "sendType", value = "配送方式【用户版】。1门店配送（默认），2自提") @RequestParam(value="sendType",required=false) Integer sendType,
                        @ApiParam(required = false, name = "couponId", value = "优惠券Id[用户版]") @RequestParam(value="couponId",required=false) Long couponId,
                        @ApiParam(required = false, name = "isUsedBalance", value = "是否使用余额。[用户版]0否，1是") @RequestParam(value="isUsedBalance",required=false) Integer isUsedBalance,
                        @ApiParam(required = false, name = "addressId", value = "收货地址Id。【用户版】选择配送或【管理版】下单，需要传入") @RequestParam(value="addressId",required=false) Long addressId,
                        @ApiParam(required = false, name = "villageId", value = "小区ID。[用户版]") @RequestParam(value="villageId",required=false) Long villageId,
                        @ApiParam(required = false, name = "payPassword", value = "支付密码。[用户版]使余额抵扣传入") @RequestParam(value="payPassword",required=false) String payPassword,
                        @ApiParam(required = false, name = "remark", value = "订单备注。") @RequestParam(value="remark",required=false) String remark,
                         @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                         @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{

            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            StringBuilder cartIdsStr=new StringBuilder();
            for(Long cartId:cartIds){
                cartIdsStr.append(cartId+",");
            }
            param.put("cartIds",cartIdsStr.substring(0,cartIdsStr.length()-1).toString());//实际是字符串。cartIds=1,2,3
            param.put("sendType",sendType);
            param.put("couponId",couponId);
            param.put("isUsedBalance",isUsedBalance);
            param.put("addressId",addressId);
            param.put("villageId",villageId);
            param.put("payPassword",payPassword);
            param.put("remark",remark);
            param.put("nonce", nonce);
            param.put("sign", sign);
           /* boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/

            Long memberId = AccountIdHoldUtils.getMemberId();
            Map<String,Object> result = orderService.createOrder(memberId,cartIds,
                    sendType, couponId, isUsedBalance, addressId, villageId,
                    payPassword, remark);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/order/createOrder----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/select",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】分页获取订单。")
    public void select(HttpServletRequest request,
                            HttpServletResponse response,
                            @ApiParam(required = true, name = "type", value = "订单类型。1,用户自己的商城订单，2用户自己的积分订单，3，门店/大客户自己的采购订单，4，门店的配送订单") @RequestParam(value = "type", required = true)Integer type,
                            @ApiParam(required = true, name = "orderStatuses", value = "订单状态集合，支持传入多个状态。例如：orderStatuses=1,2,3" +
                            "0全部，1，待付款，2待配送，3配送中，4待评价，5已评价，6待退款， 7已退款，8待退货，9已退货,10已取消") @RequestParam(value="orderStatuses",required=true) List<Integer> orderStatuses,
                            @ApiParam(required = false, name = "createTime_start", value = "查询参数。开始时间。默认为空") @RequestParam(value = "createTime_start", required = false) String createTime_start,
                            @ApiParam(required = false, name = "createTime_end", value = "查询参数。结束时间。默认为空") @RequestParam(value = "createTime_end", required = false) String createTime_end,

                            @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
                            @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
                            @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
                            @ApiParam(required = false, name = "order", value = "排序参数。。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
                            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
            List<KitchenOrderDto> result=orderService.selectOrder(request,memberId,type,orderStatuses);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/order/select----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/findOne",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】查看订单详情。")
    public void findOne(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required = true, name = "orderId", value = "订单Id") @RequestParam(value = "orderId", required = true)Long orderId,
                        @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
            KitchenOrderDto result=orderService.findOne(orderId,memberId);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/order/findOne----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/cancel",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】取消订单。1用户商城订单，【待付款】才能取消，2用户积分订单，不能取消，3管理版【采购订单】待配送才能取消。")
    public void cancel(HttpServletRequest request,
                            HttpServletResponse response,
                            @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
           /* if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.cancelOrder(orderId,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/order/cancel----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/sendOrder",method= RequestMethod.POST)
    @ApiOperation(value="【管理版】配送订单。type==1,orderStatus==2才能配送。")
    public void sendOrder(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                          @ApiParam(required = false,name = "driverId", value = "配送员Id(商城订单-待配送-非自提订单，需要选择配送员)") @RequestParam(value = "driverId", required = false) Long driverId,

                          @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);
            param.put("driverId",driverId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
           /* if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.sendOrder(orderId,driverId,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/order/sendOrder----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/confirmReceive",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】确认收货。配送中订单才能确认收货，不区分订单类型。")
    public void confirmReceive(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                       @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {

        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);

            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
          /*  if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.confirmReceive(orderId,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;

            }else{
                logger.error("/kitchen/mobile/order/confirmReceive----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/comment",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】评论订单，每个商品最大传入三张图片，没有图片的评论，用noImage字符串，固定images集合占位。")
    public void comment(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true)Long orderId,
                       @ApiParam(required = true, name = "productIds", value = "商品ID集合(productIds,contents,scores大小，顺序对应)。例如：productIds=1,2,3") @RequestParam(value = "productIds", required = true) List<Long> productIds,
                       @ApiParam(required = true, name = "contents", value = "评论内容集合，默认值：系统默认好评。(productIds,contents,scores大小，顺序对应)。例如：contents=1,2,3") @RequestParam(value = "contents", required = true) List<String> contents,
                       @ApiParam(required = true, name = "scores", value = "评分(0-5)集合。默认值：5。（productIds,contents,scores大小，顺序对应）。例如：scores=1,2,3") @RequestParam(value = "scores", required = true)List<Integer> scores,
                       @ApiParam(required = true, name = "images", value = "图片集合；，固定大小=productIds集合大小*3。每个商品限制最大传入三张，没有图片的使用noImage字符传固定值，在集合中占位") @RequestParam(value = "images", required = true)List<String> images,
                       @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.commentOrder(orderId,productIds, contents,scores,images,memberId,nonce,sign);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/order/comment----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/getOrderNumber",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】获取给订单状态数量。")
    public void getOrderNumber(HttpServletRequest request,
                        HttpServletResponse response,
                        @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
            Map<String,Object> result=orderService.getOrderNumber(memberId);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/order/getOrderNumber----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/getRevenue",method= RequestMethod.POST)
    @ApiOperation(value="【管理版】获取营收统计的7个统计数据。含今日的和额总的")
    public void getRevenue(HttpServletRequest request,
                        HttpServletResponse response,
                        @ApiParam(required = true, name = "type", value = "1,获取今日信息（今日销售订单和今日销售总额）" +
                        "2，获取总收益，总销售订单，总销售总额，采购实付总金额，采购实付总金额") @RequestParam(value = "type", required = true)Integer type,
                        @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
            Map<String,Object> result=orderService.getRevenue(memberId,type);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/order/getRevenue----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/getRevenueDetail",method= RequestMethod.POST)
    @ApiOperation(value="【管理版】获取营收统计的明细列表。可以按日期分页查询，采购和销售明细")
    public void getRevenueDetail(HttpServletRequest request,
                           HttpServletResponse response,
                        @ApiParam(required = true, name = "type", value = "1采购明细，2销售明细") @RequestParam(value = "type", required = true)Integer type,
                        @ApiParam(required = false, name = "createTime_start", value = "查询参数。开始时间。默认为空") @RequestParam(value = "createTime_start", required = false) String createTime_start,
                        @ApiParam(required = false, name = "createTime_end", value = "查询参数。结束时间。默认为空") @RequestParam(value = "createTime_end", required = false) String createTime_end,

                        @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
                        @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
                        @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
                        @ApiParam(required = false, name = "order", value = "排序参数。。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,

                        @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
            Map<String,Object> result=orderService.getRevenueDetail( request, memberId, type);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/order/getRevenueDetail----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    /**
     * --------------2017年9月7日新增
     */
    @RequestMapping(value="/sendOrderWeb",method= RequestMethod.POST)
    @ApiOperation(value="【PC后台】配送订单。type==1,orderStatus==2才能配送。")
    public void sendOrderWeb(HttpServletRequest request,
                          HttpServletResponse response,
                          @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                          @ApiParam(required = false,name = "driverId", value = "配送员Id(商城订单-待配送-非自提订单，需要选择配送员)") @RequestParam(value = "driverId", required = false) Long driverId
    ) {
        try{
            orderService.send_order_mall_web(orderId,driverId,null);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/order/sendOrderWeb----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
}
